package com.cjr.mq.cases.service;

import com.cjr.mq.cases.entity.OrderInfo;
import com.cjr.mq.cases.entity.OrderStatusEnum;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class OrderServiceImpl implements OrderService {
    /**
     * 模拟数据库
     */
    private static volatile List<OrderInfo> orderList = new ArrayList<>();

    // 根据orderId修改订单状态
    @Override
    public void updateOrderStatus(String orderId, String flag) {
        try {
            // 业务代码
            orderList.stream().filter(orderInfo -> {
                if (orderId.equals(orderInfo.getOrderId())) {
                    if ("cancle".equals(flag)) {
                        orderInfo.setOrderStatus(OrderStatusEnum.HAS_CANCEL.getFlag());
                    }else if ("pay".equals(flag)) {
                        orderInfo.setOrderStatus(OrderStatusEnum.HAS_PAY.getFlag());
                    }
                }
                return true;
            }).collect(Collectors.toList());

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    // 创建订单
    @Override
    public void createOrder(String orderId) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        final OrderInfo orderInfo = new OrderInfo();
        orderInfo.setSeq(formatter.format(LocalDateTime.now()) + orderId);
        orderInfo.setOrderId(orderId);
        orderInfo.setOrderStatus(OrderStatusEnum.WAIT_PAY.getFlag());
        orderInfo.setOrderName("Jack");
        orderInfo.setCreateDate(LocalDateTime.now().toString());
        orderInfo.setOrderAmt("600");
        orderList.add(orderInfo);
    }

    // 根据订单号查询订单
    @Override
    public OrderInfo findOrderByOrderId(String orderId) {
        for (final OrderInfo orderInfo : orderList) {
            if (orderId.equals(orderInfo.getOrderId())) {
                return orderInfo;
            }
        }
        return null;
    }

    @Override
    public List findAll() {
        return orderList;
    }
}
